﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.UserProfiles.Caching;
using Core.Identity.UserProfiles.Dtos;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.UserProfiles.Features.Queries.GetById;

/// <summary>
/// 获取用户偏好
/// </summary>
public class GetUserProfileByIdQuery : ICacheableRequest<Result<List<UserPreferenceDto>>>
{
    public Guid UserId { get; set; }

    /// <summary>
    /// 缓存键
    /// </summary>
    [JsonIgnore]
    public string CacheKey => UserProfilesCacheKey.GetUserProfileCacheKey(UserId.ToString());

    /// <summary>
    /// 缓存选项
    /// </summary>
    [JsonIgnore]
    public IEnumerable<string> Tags => UserProfilesCacheKey.Tags!;
}

public class GetUserProfileByIdQueryHandler(IIdentityDbContext dbContext) : IRequestHandler<GetUserProfileByIdQuery, Result<List<UserPreferenceDto>>>
{

    public async Task<Result<List<UserPreferenceDto>>> Handle(GetUserProfileByIdQuery request, CancellationToken cancellationToken)
    {
        var profile = await dbContext.UserProfiles
            .Include(x => x.Preferences)
            .FirstOrDefaultAsync(x => x.UserId == request.UserId, cancellationToken);

        var result = profile?.Preferences
             .Select(p => new UserPreferenceDto
             {
                 Key = p.Key,
                 Value = p.GetValue<object>(),
                 Description = p.Description
             })
             .ToList()
             ?? new List<UserPreferenceDto>();

        return await Result<List<UserPreferenceDto>>.SucceedAsync(result);
    }
}
